/**
 * @file drv_tim_encoder.c
 * @brief HAL CUBEMX DRIVER
 * 
 * @author dalin (dalin@open-robot.com)
 * @version 1.0
 * @date 2023-05-10
 * 
 * @copyright Copyright (c) 2023  Open Robot Tech.co, Ltd
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2023-05-10 <td>1.0     <td>dalin     <td>初始化
 * </table>
 */

#include "drv_tim_encoder.h"
#ifdef USE_TIM_ENCODER_DRIVER

#include "tim.h"
#include "mlog.h"

/**
 * @brief 打开编码器捕获
 * 
 * @param  tim              : tim编号（timNumber_e）
 * @param  channel          : 指定通道 （timChannel_e）
 * 
 * @return int 成功：DRV_EOK  失败：其他
 */
int drv_tim_encoder_start(timNumber_e tim, timChannel_e channel)
{
    TIM_HandleTypeDef *handle;
    uint32_t ch;

    handle = get_tim_handle(tim);
    if(handle == NULL)
    {
        return DRV_ERROR;
    }
    ch = get_tim_channel(channel);

    /* PWM启动函数 */
    HAL_TIM_Encoder_Start(handle, ch);

    return DRV_EOK;
}

/**
 * @brief 编码器反向时，转为与正向时对应的负数
 * 
 */
static void encoder_porcess(int *cnt)
{
  if(*cnt > FULL_ENCODER * 0.5f)
    *cnt = *cnt - FULL_ENCODER ; 
}

/**
 * @brief 获取编码器速度
 * 
 * @param  tim              : tim编号（timNumber_e）
 * @param  channel          : 速度
 * 
 * @return int 成功：DRV_EOK  失败：其他
 */
int drv_tim_encoder_speed(timNumber_e tim, int *speed)
{
    TIM_HandleTypeDef *handle;
    int cnt;

    handle = get_tim_handle(tim);
    if(handle == NULL)
    {
        return DRV_ERROR;
    }

    cnt = (int)__HAL_TIM_GET_COUNTER(handle);
	__HAL_TIM_SET_COUNTER(handle,0);

    encoder_porcess(&cnt);
    *speed = cnt;

    return  DRV_EOK;
}



#endif /* USE_ENCODER_DRIVER */
